package com.gccloud.tgyfirst.service.demo.service.impl;

import com.gccloud.tgyfirst.demo.dto.CourseDTO;
import com.gccloud.tgyfirst.demo.entity.CourseEntity;
import com.gccloud.tgyfirst.service.demo.service.ICourseService;
import com.gccloud.tgyfirst.service.demo.service.IImportAndExportService;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.gccloud.starter.common.exception.GlobalException;
import com.gccloud.starter.common.utils.BeanConvertUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author qianxing
 * @version 1.0
 * @date 2021/5/19 9:39
 */
@Service
public class ImportAndExportServiceImpl implements IImportAndExportService {

    @Resource
    private ICourseService courseService;

    @Override
    public void importFromExcel(InputStream inputStream) {
        try {
            // 读取第一个sheet页
            ExcelReader excelReader = ExcelUtil.getReader(inputStream, 0);
            List<Map<String, Object>> list = excelReader.readAll();
            int count = 0;
            for (Map<String, Object> map : list) {
                count++;
                CourseDTO courseDTO = new CourseDTO();
                try {
                    BeanUtils.populate(courseDTO, map);
                } catch (Exception e) {
                    throw new GlobalException("导入出错！");
                }
                CourseEntity entity = BeanConvertUtils.convert(courseDTO, CourseEntity.class);
                // 导入的时候没添加租户id和机构id
                courseService.add(entity);
            }
        } catch (Exception e) {
            throw new GlobalException("导入出错！");
        }
    }

}
